# -*- coding: utf-8 -*-

import logging
import threading

from global_data.constant_data import ConstantData
from global_data.glabal_data import GlobalData
from utils.file_utils import FileUtils

"""
日志封装
1、默认调用  对应文件名  log
IcloudpLog.error("cls-类方法调用")
IcloudpLog.info("cls-类方法调用")
2、实例调用  --1
log = IcloudpLog.get_logger("monitor_log")  # 实例化对象   参数为文件名    get_logger是类方法
log.set_info("monitor-实例方法调用")
3、实例调用  --2                                                             推荐
log = IcloudpLog("sys_log").logger  获取实例对象  同2
log.error("sys-实例方法调用")
4、模块实例                                                                    推荐
IcloudpLog.get_logger_sys().error("cls-类方法调用")
IcloudpLog.get_logger_config().error("cls-类方法调用")
IcloudpLog.get_logger_zmq().error("cls-类方法调用")


"""


class IcloudpLog(object):
    log_colors_config = {
        'DEBUG': 'cyan',
        'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'red',
    }

    # 日志级别关系映射
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'warn': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    @classmethod
    def debug(cls, msg, *args, **kwargs):
        IcloudpLog.get_logger().debug(msg, *args, **kwargs)

    @classmethod
    def info(cls, msg, *args, **kwargs):
        IcloudpLog.get_logger().info(msg, *args, **kwargs)

    @classmethod
    def warn(cls, msg, *args, **kwargs):
        IcloudpLog.get_logger().warning(msg, *args, **kwargs)

    @classmethod
    def warning(cls, msg, *args, **kwargs):
        IcloudpLog.get_logger().warning(msg, *args, **kwargs)

    @classmethod
    def error(cls, msg, *args, **kwargs):
        IcloudpLog.get_logger().error(msg, *args, **kwargs)

    @classmethod
    def get_logger(cls, log_name="log"):
        log = IcloudpLog(log_name).logger
        # log.info(f"工作路径={ConstantData.WORK_PATH}， 工作路径2={GlobalData.WORK_PATH_COMMON}")
        return log

    @classmethod
    def get_logger_db(cls):
        return IcloudpLog(ConstantData.LOG_TYPE["db"]).logger

    @classmethod
    def get_logger_sys(cls):
        return IcloudpLog(ConstantData.LOG_TYPE["sys"]).logger

    @classmethod
    def get_logger_monitor(cls):
        return IcloudpLog(ConstantData.LOG_TYPE["monitor"]).logger

    @classmethod
    def get_logger_config(cls):
        return IcloudpLog(ConstantData.LOG_TYPE["config"]).logger

    @classmethod
    def get_logger_common(cls):
        return IcloudpLog(ConstantData.LOG_TYPE["common"]).logger

    @classmethod
    def get_logger_zmq(cls):
        return IcloudpLog(ConstantData.LOG_TYPE["zmq"]).logger

    @classmethod
    def get_logger_service(cls):
        return IcloudpLog(ConstantData.LOG_TYPE["service"]).logger

    # def __init__(self, log_name="log"):
    #     # print(f"__init__  pp={log_name}")
    #     # self.log_name = log_name
    #     # self.__config_logger(log_name)
    #     pass

    def __new__(cls, log_name="my_logger"):
        mutex = threading.Lock()
        mutex.acquire()  # 上锁，防止多线程下出问题
        if not hasattr(cls, 'instance') or (hasattr(cls.instance, 'log_name') and cls.instance.log_name != log_name):
            cls.instance = super(IcloudpLog, cls).__new__(cls)
            cls.instance.log_name = log_name
            cls.instance.__config_logger()
        mutex.release()
        return cls.instance

    def __get_logger(self, log_name="my_logger"):
        return self.logger

    def set_debug(self, msg, *args, **kwargs):
        self.logger.debug(msg, *args, **kwargs)

    def set_info(self, msg, *args, **kwargs):
        self.logger.info(msg, *args, **kwargs)

    def set_warn(self, msg, *args, **kwargs):
        self.logger.warning(msg, *args, **kwargs)

    def set_warning(self, msg, *args, **kwargs):
        self.logger.warning(msg, *args, **kwargs)

    def set_error(self, msg, *args, **kwargs):
        self.logger.error(msg, *args, **kwargs)

    def __config_logger(self):
        # 创建一个logger
        self.logger = logging.getLogger(self.log_name)
        self.logger.setLevel(IcloudpLog.level_relations[GlobalData.LOG_LEVEL])  # 设置日志级别

        # 创建一个handler，用于将日志写入磁盘文件
        file_handler = logging.FileHandler(FileUtils.get_new_path(f'{GlobalData.LOG_BASE_PATH}/{self.log_name}.log'))
        file_handler.setLevel(IcloudpLog.level_relations[GlobalData.LOG_LEVEL])

        # 创建一个handler，用于将日志输出到控制台
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(IcloudpLog.level_relations[GlobalData.LOG_LEVEL])  # 只输出错误到控制台

        formatter = logging.Formatter('%(asctime)s - %(name)s - [%(filename)s:%(lineno)s]%(levelname)s - %(message)s')
        file_handler.setFormatter(formatter)

        # 设置日志格式
        # formatter1 = ColoredFormatter(
        #             '%(log_color)s [%(asctime)s] [%(filename)s:%(lineno)d] [%(levelname)s]- %(message)s',
        #             datefmt=None,
        #             reset=True,
        #             log_colors=log_colors_config)  # 日志输出格式
        stream_handler.setFormatter(formatter)

        # 将handlers添加到logger
        self.logger.addHandler(file_handler)
        self.logger.addHandler(stream_handler)


if __name__ == '__main__':
    print("Python")
